package com.knowif.backend.scheduled;

import com.alibaba.fastjson.JSONObject;
import com.knowif.backend.service.FastAskOrderService;
import com.knowif.backend.service.UserOrderFlowService;
import com.knowif.enumInfo.UserOrderStatusEnum;
import com.knowif.pojo.*;
import com.knowif.service.UserPayOrder_service;
import com.knowif.util.WechatMiniUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class WechatTask {
    @Autowired
    private ServletContext servletContext;
    @Autowired
    private WechatMiniUtil wechatMiniUtil;
    @Autowired
    private UserPayOrder_service userPayOrderService;
    @Autowired
    private UserOrderFlowService userOrderFlowService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private FastAskOrderService fastAskOrderService;

    @Value("${wechat.config.constant.refundNotifyUrl}")
    private String refundNotifyUrl;//退款异步处理地址

    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void setAccessToken() {
        String accessToken = wechatMiniUtil.getAccessToken();
        String wechatAccessToken = wechatMiniUtil.getPlatformAccessToken();
        servletContext.setAttribute("accessToken", accessToken);
        servletContext.setAttribute("wechatAccessToken", wechatAccessToken);
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        stringStringValueOperations.set("accessToken", accessToken);
        stringStringValueOperations.set("wechatAccessToken", wechatAccessToken == null ? "" : wechatAccessToken);
        log.info("{}","微信小程序 AccessToken ================>" + accessToken);
        log.info("{}","微信公众号 AccessToken ================>" + wechatAccessToken);
    }

    /**
     * 失效订单查询 频率：1h
     **/
    @Scheduled(fixedRate = 60 * 60 * 1000)
    public void orderExpiredCheck() {
        List<UserOrder> orders = userPayOrderService.getUserOrderByStatus(UserOrderStatusEnum.BEGIN.getState());
        if (orders != null && !orders.isEmpty()) {
            for (UserOrder userOrder : orders) {
                UserOrderStatus status = userPayOrderService.getUserOrderStatusByOrderId(userOrder.getId(), UserOrderStatusEnum.BEGIN.getState());
                if (status != null) {
                    Date date = status.getCreateTime();
                    Date nowDate = new Date();
                    long diff = nowDate.getTime() - date.getTime();
                    long days = diff / (1000 * 60 * 60 * 24);
                    if (days >= 3) {
                        //在这里通知 订单超过72h失效
                        UserOrder order = userPayOrderService.selectUserOrderById(status.getUserOrderId());
                        if (order != null) {
                            order.setStatus(UserOrderStatusEnum.INVALID.getState());
                            userPayOrderService.updateOrder(order);
                        }
                    }
                }
            }
        }

    }

    /**
     * 自动取消订单频率 1 h 延迟 3分钟
     */
    @Scheduled(fixedRate = 30 * 60 * 1000)
    public void autoCancelOrder() {
        List<UserOrder> orders = userPayOrderService.getUserOrderByStatus(UserOrderStatusEnum.PAID.getState());
        if (orders != null && !orders.isEmpty()) {
            for (UserOrder userOrder : orders) {
                UserOrderStatus status = userPayOrderService.getUserOrderStatusByOrderId(userOrder.getId(), UserOrderStatusEnum.PAID.getState());
                if (status != null) {
                    Date date = status.getCreateTime();
                    Date nowDate = new Date();
                    long diff = nowDate.getTime() - date.getTime();
                    long days = diff / (1000 * 60 * 60 * 24);
                    //long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
                    if (days >= 1) {
                        //退款
                        UserOrderFlow userOrderFlow = userPayOrderService.selectUserOrderFlowByUserOrderId(userOrder.getId());
                        int price = new Double(userOrder.getPrice() * 100).intValue();
                        userOrderFlowService.payRefund(userOrderFlow.getWechatTradeNo(), price, price, refundNotifyUrl, "超时确认订单，全额退款");
                    }
                }
            }
        }
    }

    /**
     * 自动确认订单
     */
    @Scheduled(fixedRate = 68 * 60 * 1000)
    public void autoConfirmOrderEval() {
        List<UserOrder> orders = userPayOrderService.getUserOrderByStatus(5);
        if (orders != null && !orders.isEmpty()) {
            for (UserOrder userOrder : orders) {
                UserOrderStatus status = userPayOrderService.getUserOrderStatusByOrderId(userOrder.getId(), 5);
                if (status != null) {
                    Date date = status.getCreateTime();
                    Date nowDate = new Date();
                    long diff = nowDate.getTime() - date.getTime();
                    long days = diff / (1000 * 60 * 60 * 24);
                    if (days >= 7) {
                        userOrder.setStatus(8);
                        userPayOrderService.updateOrder(userOrder);
                    }
                }
            }
        }
    }

    /**
     * /**
     * 自动取消快问超时订单 1 h 延迟 3分钟
     */
    @Scheduled(fixedRate = 30 * 60 * 1000)
    public void autoCancelFastAskOrder() {
        FastAskOrderExample example = new FastAskOrderExample();
        //已支付未回答的订单
        example.createCriteria().andStatusEqualTo(1);
        List<FastAskOrder> data = fastAskOrderService.query(example);
        log.info("需要退款的订单" + JSONObject.toJSONString(data));
        if (data != null && !data.isEmpty()) {
            for (FastAskOrder fastAskOrder : data) {
                Date date = fastAskOrder.getCreateTime();
                Date nowDate = new Date();
                long diff = nowDate.getTime() - date.getTime();
                long days = diff / (1000 * 60 * 60 * 24);
                //long hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
                //大于48小时退款
                if (days >= 2) {
                    //退款
                    fastAskOrderService.refund(fastAskOrder);
                }
            }
        }
    }


}
